import org.codehaus.groovy.grails.plugins.springsecurity.Secured
import grails.converters.JSON
import com.st.utils.DataList

// TODO: modify to allow user also.
@Secured(['ROLE_ADMIN', 'ROLE_POWER_USER'])
class AddressController {
    
    def authenticateService

    // the delete, save and update actions only accept POST requests
    static allowedMethods = [delete:'POST', save:'POST', update:'POST']

    /** VIEWS **/
    def index = {redirect uri:'/'}

    // List Views
    def list = {
        redirect uri:'/' 
    }

    // Show Views
    def show = {
        println params
        def address = Address.get(params.id)
        def company = Company.get(params.companyId)

        if (!address) {
            flash.message = "Address not found with id ${params.id}"
            redirect(action:list)
        } else {
            return [address:address, company:company, addressType:params.addressType]
        }
    }

    // Create/Edit Views
    @Secured(['ROLE_ADMIN', 'ROLE_POWER_USER'])
    def create = {
    }

    def edit = {
        def address = Address.get(params.id)
        def company = Company.get(params.companyId)

        if(!address) {
            flash.message = "Address not found with id ${params.id}"
            redirect(action:list)
        }
        else {
            return [address:address, company:company, addressType:params.addressType]
        }
    }

    /** ACTIONS **/
    // Save/Update/Delete Actions
    def update = {
        def address = Address.get(params.id)

        if(address) {
            if(params.version) {
                def version = params.version.toLong()
                if(address.version > version) {
                    
                    address.errors.rejectValue("version", "address.optimistic.locking.failure", "Another user has updated this Address while you were editing.")
                    render(view:'edit',model:[address:address])
                    return
                }
            }
            address.properties = params
            if(!address.hasErrors() && address.save()) {
                flash.message = "Address ${params.id} updated"
                redirect(action:show, params:[id:params.id, companyId:params.companyId, addressType:params.addressType])
            }
            else {
                render(view:'edit',model:[address:address])
            }
        }
        else {
            flash.message = "Address not found with id ${params.id}"
            redirect(action:list)
        }
    }

    /** JSON DATA **/
    def listPostalCodesForACAsJSON = {
        def list = Address.findAllByPostalCodeIlike("${params.query}%").postalCode.unique()
        list = list.collect {
            [id:it, name:it]
        }
        render DataList.createList(list) as JSON
    }
}
